import { Euler } from './three.module.js';

const defAttr = () => ({
    btn: null,
    noDevice: () => { console.log('设备没有陀螺仪!') },//没有陀螺仪
    onClick: () => { },//点击按钮(无)
    init: () => { },//初始化
    reject: () => { console.log('未获取到许可!') },//拒绝开启陀螺仪
    error: () => { console.log('请求失败') },//请求失败
    change: (euler) => { },//陀螺仪变换
});

//陀螺仪
export default class Gyro {
    constructor(attr) {
        Object.assign(this, defAttr(), attr);
    }

    start() {
        if (window.DeviceMotionEvent) {
            //ios需要请求用户许可
            if (DeviceMotionEvent.requestPermission) {
                this._requestPermission();
            } else {
                this._translate();
            }
        } else {
            this.noDevice();
        }
    }

    //请求ios许可
    _requestPermission() {
        DeviceMotionEvent.requestPermission().then((permissionState) => {
            if (permissionState === 'granted') {
                this._translate();
            } else {
                this.reject();
            }
        }).catch((err) => {
            this.error(err);
        });
    }

    //陀螺仪旋转
    _translate() {
        this.init();
        window.addEventListener('deviceorientation', ({ alpha, beta, gamma }) => {
            const rad = Math.PI / 180;
            // beta = x, alpha = y, gamma = z,(W3C标准)
            //左手坐标系
            //先用世界坐标系绕Y旋转
            //再用本地坐标系绕X旋转
            //后用本地坐标系绕Z旋转
            // 'YXZ' 表示Y轴先转
            const euler = new Euler(beta * rad, alpha * rad, -gamma * rad, 'YXZ');
            this.change(euler);
        })
    }

}